-- Standard awesome library
local gears = require("gears")
local awful = require("awful")
require("awful.autofocus")
require("awful.spawn")
-- Widget and layout library
local wibox = require("wibox")
-- Theme handling library
local beautiful = require("beautiful")
-- Notification library
--local naughty = require("naughty")
local menubar = require("menubar")
local hotkeys_popup = require("awful.hotkeys_popup").widget
-- Enable hotkeys help widget for VIM and other apps
-- when client with a matching name is opened:
require("awful.hotkeys_popup.keys")

-- {{{ Error handling
-- Check if awesome encountered an error during startup and fell back to
-- another config (This code will only ever execute for the fallback config)
if awesome.startup_errors then
    naughty.notify({ preset = naughty.config.presets.critical,
                     title = "Oops, there were errors during startup!",
                     text = awesome.startup_errors })
end

-- Handle runtime errors after startup
do
    local in_error = false
    awesome.connect_signal("debug::error", function (err)
        -- Make sure we don't go into an endless error loop
        if in_error then return end
        in_error = true

        naughty.notify({ preset = naughty.config.presets.critical,
                         title = "Oops, an error happened!",
                         text = tostring(err) })
        in_error = false
    end)
end
-- }}}

beautiful.init("/home/alex/.config/awesome/theme/theme.lua")

terminal = "kitty"
editor = os.getenv("EDITOR") or "nano"
editor_cmd = terminal .. " -e " .. editor
modkey = "Mod4"
altkey = "Mod1"

awful.layout.layouts = {
    -- awful.layout.suit.floating,
    awful.layout.suit.tile,
    -- awful.layout.suit.tile.left,
    -- awful.layout.suit.tile.bottom,
    -- awful.layout.suit.tile.top,
    -- awful.layout.suit.fair,
    -- awful.layout.suit.fair.horizontal,
    -- awful.layout.suit.spiral,
    -- awful.layout.suit.spiral.dwindle,
    -- awful.layout.suit.max,
    -- awful.layout.suit.max.fullscreen,
    -- awful.layout.suit.magnifier,
    -- awful.layout.suit.corner.nw,
    -- awful.layout.suit.corner.ne,
    -- awful.layout.suit.corner.sw,
    -- awful.layout.suit.corner.se,
}

local function set_wallpaper(s)
    if beautiful.wallpaper then
        local wallpaper = beautiful.wallpaper
        -- if wallpaper is a function, call it with the screen
        if type(wallpaper) == "function" then
            wallpaper = wallpaper(s)
        end
        gears.wallpaper.maximized(wallpaper, s, true)
    end
end

-- reset wallpaper when screen geometry changes
screen.connect_signal("property::geometry", set_wallpaper)

awful.screen.connect_for_each_screen(function(s)
    set_wallpaper(s)

    -- each screen has its own set of desktops
    awful.tag({
        "1",
        "2",
        "3",
        "4",
        "5",
        "6",
        "7",
        "8",
        "9",
    }, s, awful.layout.layouts[1])
end)

function do_border_radius(c)
    if beautiful.border_radius and not c.fullscreen then
        -- rounded corners
        c.shape = function (cr, w, h)
            gears.shape.rounded_rect(cr, w, h, beautiful.border_radius)
        end
    else
        c.shape = nil
    end
end

-- keybindings
globalkeys = gears.table.join(
    --[[
    awful.key({ altkey }, "Tab", function ()
        awful.client.focus.history.previous()
        if client.focus then
            client.focus:raise()
        end
    end),
    --]]

    awful.key({ modkey, "Shift" }, "Return", function () awful.spawn(terminal) end),
    awful.key({ altkey }, " ", function () awful.spawn("rofi -show run") end),
    awful.key({}, "Print", function () awful.spawn("screenshot-area") end),
    awful.key({ "Shift" }, "Print", function () awful.spawn("color-picker") end),

    awful.key({ modkey, "Control" }, "r", awesome.restart),
    awful.key({ modkey, "Control" }, "q", awesome.quit)
)

-- window-specific keybindings
clientkeys = gears.table.join(
    awful.key({ modkey }, " ", function (c)
        c.fullscreen = not c.fullscreen
        do_border_radius(c)
        c:raise()
    end),

    awful.key({ modkey, "Shift" }, "q", function (c) c:kill() end)
)

-- multiple desktops
for i = 1, 9 do
    globalkeys = gears.table.join(globalkeys,
        -- view desktop -- mod+#
        awful.key({ modkey }, "#" .. i + 9, function ()
            local screen = awful.screen.focused()
            local tag = screen.tags[i]
            if tag then
                tag:view_only()
            end
        end),

        -- move window to desktop -- mod+shift+#
        awful.key({ modkey, "Shift" }, "#" .. i + 9, function ()
            if client.focus then
                local tag = client.focus.screen.tags[i]
                if tag then
                    client.focus:move_to_tag(tag)
                end
            end
        end)
    )
end

clientbuttons = gears.table.join(
    awful.button({}, 1, function (c) client.focus = c; c:raise() end),
    awful.button({ altkey }, 1, awful.mouse.client.move),
    awful.button({ altkey }, 3, awful.mouse.client.resize))

-- window rules
awful.rules.rules = {
    -- default properties
    { rule = {
        -- all
    }, properties = {
        border_width = beautiful.border_width,
        border_color = beautiful.border_normal,
        focus = awful.client.focus.filter,
        raise = true,
        keys = clientkeys,
        buttons = clientbuttons,
        screen = 1,
        titlebars_enabled = true,
        floating = false,
        placement = awful.placement.no_overlap+awful.placement.no_offscreen
    }},

    -- centred dialogs
    { rule_any = {
        type = {
            "dialog",
        },
        name = {
            "Save As",
        },
        role = {
            "GtkFileChooserDialog",

        },
        class = {
            "Rofi",
        },
    }, properties = {
        floating = true,
        ontop = true,
        sticky = true,
        --titlebars_enabled = true,
    }, callback = function (c)
        awful.placement.centered(c, { honor_workarea=true })
    end },

    -------------------------- application-specific ----------------------------

    { rule_any = {
        class = { "Firefox Developer Edition", "Sublime_text" },
    }, properties = { tag = "1", titlebars_enabled = false } },

    { rule_any = {
        class = { "discord" },
    }, properties = { tag = "2", titlebars_enabled = false } },

    { rule_any = {
        class = { "Inkscape", "allegro" }, -- see github/aseprite#1942
    }, properties = { tag = "3" } },

    { rule_any = {
        class = { "Steam" },
    }, properties = { tag = "6" } },
}

client.connect_signal("manage", function (c)
    if awesome.startup and
      not c.size_hints.user_position
      and not c.size_hints.program_position then
        -- prevent clients from being unreachable when a screen is disconnected
        awful.placement.no_offscreen(c)
    end

    do_border_radius(c)
end)

-- titlebars
client.connect_signal("request::titlebars", function(c)
    local drag2move = gears.table.join(
        awful.button({ }, 1, function()
            client.focus = c
            c:raise()
            awful.mouse.client.move(c)
        end),
        awful.button({ }, 3, function()
            client.focus = c
            c:raise()
            awful.mouse.client.resize(c)
        end)
    )

    local horiz = wibox.layout.flex.horizontal

    awful.titlebar(c, { size = 36 }) : setup {
        { buttons = drag2move, layout = horiz }, -- left
        {
            {
                -- title
                align  = "center",
                widget = awful.titlebar.widget.titlewidget(c),
            },
            buttons = drag2move,
            layout = horiz,
        },
        { buttons = drag2move, layout = horiz }, -- right
        layout = horiz,
    }
end)

--[[
-- focus follows mouse
client.connect_signal("mouse::enter", function(c)
    if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier
        and awful.client.focus.filter(c) then
        client.focus = c
    end
end)
--]]

-- bind keys
root.keys(globalkeys)
--root.buttons(globalbuttons)
